package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    //本地存储
    @PostMapping("/uploads")
    public Result upload(String username, Integer age , MultipartFile image ) throws  Exception{

        log.info("文件上传:{},{},{}",username,age,image);
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();
         /*直接用原名存储,相同文件会覆盖
        image.transferTo(new File("D:\\java\\images\\"+originalFilename));
         */
        //重新给文件取名,防止文件名重复
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        String newString= UUID.randomUUID().toString()+substring;
        log.info("newString:{}",newString);
        //文件转存
        image.transferTo(new File("D:\\java\\images\\"+newString));
        return  Result.success();

        /*文件过大,需要修改配置
        #文件上传的大小
            spring.servlet.multipart.max-file-size=10MB
        #多个文件上传的大小
            spring.servlet.multipart.max-request-size=100MB
         */
    }

        //阿里云存储
        @PostMapping("/upload")
    public Result uploadAli(MultipartFile image) throws IOException {
        log.info("文件上传:{}",image.getOriginalFilename());
        String url = aliOSSUtils.upload(image);
        log.info("上传完成,路径:{}",url);
        return Result.success(url);
    }

}
